const Router = require('koa-router');
const dayjs = require('dayjs');
const isSameOrBefore = require('dayjs/plugin/isSameOrBefore');
const Models = require('../Models/model');
const Work = Models.getModel('work');

let workRouter = new Router();
dayjs.extend(isSameOrBefore);

const _filter = {
	__v: 0
};

workRouter.post('/addWork', async ctx => {
	let resData = ctx.request.body,
		error = false;
	await insertWork(resData).then(res => {
		res == null ? (error = false) : (error = true);
	});
	ctx.response.status = 200;
	ctx.response.body = error
		? {
			code: 1,
			msg: '服务器出错'
		  }
		: {
			code: 0,
			msg: '成功'
		  };
});

workRouter.get('/getWorks', async ctx => {
	let { user } = ctx.request.query,
		error = false,
		resData = [];
	await Work.find({ user }, _filter)
		.then(doc => {
			resData = doc;
		})
		.catch(() => {
			error = true;
		});
	ctx.response.body = error
		? {
			code: 1,
			msg: '服务器出错了'
		  }
		: {
			code: 0,
			data: resData
		  };
});

workRouter.post('/changeWorkStatus', async ctx => {
	let { timeStamp, user } = ctx.request.body,
		error = false;
	await Work.find({ timeStamp, user })
		.then(doc => {
			if (!doc) error = true;
			else {
				Work.findByIdAndUpdate(doc[0]._id, {
					finished: doc[0].finished ? !doc[0].finished : true
				}).catch(() => {
					error = true;
				});
			}
		})
		.catch(() => {
			error = true;
		});
	ctx.response.status = 200;
	ctx.response.body = error
		? {
			code: 1,
			msg: '服务器出错'
		  }
		: {
			code: 0,
			msg: '成功'
		  };
});

workRouter.post('/deleteWork', async ctx => {
	let id = ctx.request.body.id,
		error = false;
	await Work.findByIdAndRemove(id).catch(() => {
		error = true;
	});
	ctx.response.status = 200;
	ctx.response.body = error
		? {
			code: 1,
			msg: '服务器出错'
		  }
		: {
			code: 0,
			msg: '成功'
		  };
});

async function insertWork(data) {
	let result = null;
	await Work.find(
		{ user: data.user, workName: data.workName, workDetails: data.workDetails },
		_filter
	)
		.then(doc => {
			if (doc.length === 0) {
				Work.create({ ...data, timeStamp: new Date() }).then(doc => {});
			}
		})
		.catch(() => {
			result = true;
		});
	return result;
}

module.exports = workRouter;
